<template>
  <div>
    <el-dialog
      :title="!dataForm.id ? '课程新增' : '课程修改'"
      :close-on-click-modal="false"
      :visible.sync="visible"
      :before-close="handleClose"
    >
      <el-form
        :model="dataForm"
        :rules="dataRule"
        ref="dataForm"
        @keyup.enter.native="dataFormSubmit()"
        label-width="150px"
      >
        <el-form-item label="课程名称" prop="chapterName">
          <el-input v-model.trim="dataForm.chapterName" placeholder="课程名称"></el-input>
        </el-form-item>
        <el-form-item label="课程封面" prop="courseCoverUrl">
          <!--用于修改时把验证取消-->
          <el-input v-model="dataForm.courseCoverUrl" v-show="false"></el-input>
          <el-upload
            class="avatar-uploader"
            :action="url"
            :show-file-list="false"
            :on-success="handleUploadImageOK"
            accept="image/jpg,image/jpeg,image/png">
            <img v-if="dataForm.courseCoverUrl" :src="dataForm.courseCoverUrl" class="avatar">
            <i v-else class="el-icon-plus avatar-uploader-icon"></i>
            <div slot="tip" class="el-upload__tip">请上传图片小于250KB</div>
          </el-upload>
        </el-form-item>
        <el-form-item label="视频时长" prop="video_duration">
          <el-input v-model.trim="dataForm.video_duration" placeholder="例如: 00:40:41"></el-input>
        </el-form-item>
        <el-form-item label="上传视频"
                      prop="sourceInfo.video_url"
                      :rules="[
            { required: true, message: '视频不能为空', trigger: 'change' },
          ]">
          <el-input v-model="dataForm.sourceInfo.video_url" v-show="false"></el-input>
          <video
            v-if="dataForm.sourceInfo.video_url"
            :src="dataForm.sourceInfo.video_url"
            style="width: 185px;"
            controls="controls"
            id="myvideo"
          >您的浏览器不支持视频播放
          </video>
          <div style="color:#00f;width: 100%;overflow: hidden; " v-if="dataForm.sourceInfo.video_url!=''">
            {{dataForm.sourceInfo.video_name}}
          </div>
          <el-upload
            ref="replaceUploader"
            :file-list="replaceList1"
            :show-file-list="true"
            :action="videourl"
            :on-success="handleVideoSuccess"
            :before-upload="beforeUploadVideo"
            :on-remove="removefile1"
            :on-change="handleChange1"
          >
            <el-button size="small" type="primary">点击上传</el-button>
            <div slot="tip" class="el-upload__tip">只能上传mp4文件且大小不超过150M</div>
          </el-upload>
        </el-form-item>
        <el-form-item label="视频封面"
                      prop="sourceInfo.cover_url"
                      :rules="[
            { required: true, message: '视频封面不能为空', trigger: 'change' },
          ]">
          <el-input v-model="dataForm.sourceInfo.cover_url" v-show="false"></el-input>
          <el-upload
            class="avatar-uploader"
            :action="url"
            :show-file-list="false"
            :on-success="handleUploadImageOK1"
            accept="image/jpg,image/jpeg,image/png">
            <img v-if="dataForm.sourceInfo.cover_url" :src="dataForm.sourceInfo.cover_url" class="avatar">
            <i v-else class="el-icon-plus avatar-uploader-icon"></i>
            <div slot="tip" class="el-upload__tip">请上传图片小于250KB</div>
          </el-upload>
        </el-form-item>
        <el-form-item label="课程内容" prop="content">
          <el-input v-model="dataForm.content" v-show="false"></el-input>
          <template>
            <div class="content">
              <script :id="cueId" class="ueditor-box" type="text/plain">{{dataForm.content}}</script>
            </div>
          </template>
        </el-form-item>
      </el-form>
      <span slot="footer" class="dialog-footer">
        <el-button @click="preview()">预览</el-button>
        <el-button @click="down">取消</el-button>
        <el-button type="primary" @click="getContent()">确定</el-button>
      </span>
    </el-dialog>
    <el-dialog :close-on-click-modal="false" :visible.sync="qrcode" width="30%">
      <div class="qrcode">
        <img :src="qrimg">
      </div>
    </el-dialog>
  </div>
</template>
<style lang="scss">
  .ueditor-box {
    height: 150px;
    // width: 60%;
  }

  .qrcode {
    width: 200px;
    height: 200px;
    margin: 0 auto;
  }

  .qrcode img {
    width: 100%;
    height: 100%;
  }

  .content {
    height: 420px !important;
  }

  .avatar-uploader .el-upload {
    border: 1px dashed #d9d9d9;
    border-radius: 6px;
    cursor: pointer;
    position: relative;
    overflow: hidden;
  }

  .avatar-uploader .el-upload:hover {
    border-color: #409EFF;
  }

  .avatar-uploader-icon {
    font-size: 28px;
    color: #8c939d;
    width: 178px;
    height: 178px;
    line-height: 178px;
    text-align: center;
  }

  .avatar {
    width: 178px;
    height: 178px;
    display: block;
  }
</style>
<script>
  import ueditor from "ueditor";

  export default {
    data() {
      return {
        isAlive: '',
        visible: false,
        qrcode: false,
        dataForm: {
          id: 0,
          courseCoverUrl: '',
          video_duration: '',
          bookId: "",
          chapterName: "",
          sourceInfo: {
            video_url: "",
            video_name: '',
            cover_url: '',//视频封面URL
            cover_name: '',
          },
          content: "",
        },
        dataRule: {
          chapterName: [
            {required: true, message: "课程名称不能为空", trigger: "blur"},
            // {max: 18, message: "最长18个字符", trigger: "blur"}
          ],
          courseCoverUrl: [
            {required: true, message: "课程封面不能为空", trigger: "change"},
          ],
          content: [
            {required: true, message: "课程内容不能为空", trigger: "blur"},
          ],
          video_duration: [
            {required: true, message: "视频时长不能为空", trigger: "blur"},
            {
              pattern: /\d{2}:\d{2}:\d{2}/,
              message: "请输入正确格式",
              trigger: "blur"
            }
          ]
        },
        url: "",
        ue: null,
        cueId: `J_ueditorBox_${new Date().getTime()}`,
        ueContent: "",
        replaceList: [],
        replaceList1: [],
        replaceList2: [],
        qrimg: "", //二维码
        getQr: "",
        videourl: "", //视频url
        imageUrl: '',//图片路径
        uploadUrl: "",//上传图地址
      };
    },
    mounted() {
      this.url = this.$http.adornUrl(
        `/course/bookchapter/upload?token=${this.$cookie.get("token")}`
      );
      this.videourl = this.$http.adornUrl(
        `/course/bookchapter/uploadVideo?token=${this.$cookie.get("token")}`
      );
      this.uploadUrl = this.$http.adornUrl(
        `/course/bookchapter/uploadVideoCover?token=${this.$cookie.get("token")}`
      );
    },
    methods: {
      // 关闭窗口音频就关闭
      handleClose() {
        this.visible = false;
        this.ue.execCommand("cleardoc");
      },
      // 预览
      preview() {
        this.ue.ready(() => {
          this.ueContent = this.ue.getContent();
        });
        this.getQr = this.ueContent.replace(
          /<img/g,
          "<img style='width:100%;height:auto'"
        );
        let video = ''
        if (this.dataForm.sourceInfo.video_url) {
          video = `<div><video
            src="${this.dataForm.sourceInfo.video_url}"
            poster="${this.dataForm.sourceInfo.cover_url}"
            style="width: 100%;"
            controls="controls"
          ></video></div>`
        }
        let script = `\<script\>
function setspeed(self,speed){
let btn = document.getElementsByClassName('btn')
for(let i=0;i<btn.length;i++){
btn[i].style.background='#fff'
btn[i].style.color='#000'
}
self.style.background = '#17B3A3'
self.style.color = '#fff'
document.getElementById('audiodom').playbackRate = speed
}
\<\/script\>`
        this.$http({
          url: this.$http.adornUrl("/course/bookchapter/getQr"),
          method: "post",
          data: this.$http.adornData({
            content: video + this.getQr + script
          })
        }).then(({data}) => {
          if (data && data.code === 0) {
            this.qrcode = true;
            this.qrimg = data.qrUrl;
          } else {
            this.$message.error(data.msg);
          }
        });
      },
      handleUploadImageOK(res, file, fileList) {
        console.log(res)
        if (res && res.code === 0) {
          this.dataForm.courseCoverUrl = res.url
        } else {
          this.$message.error(res.msg)
        }
      },
      handleUploadImageOK1(res, file, fileList) {
        if (res && res.code === 0) {
          this.dataForm.sourceInfo.cover_url = res.url
        } else {
          this.$message.error(res.msg)
        }
      },
      // 取消按钮音频就关闭并且富文本清空
      down() {
        this.visible = false;
        this.ue.execCommand("cleardoc");
      },
      removefile1() {
        this.dataForm.sourceInfo.video_url = "";
      },
      removefile2() {
        this.dataForm.sourceInfo.cover_url = "";
      },
      init(bookId, id) {
        setTimeout(() => {
          this.ue = ueditor.getEditor(this.cueId, {
            zIndex: 3000
          });
        }, 100);
        this.dataForm.id = id
        this.bookId = bookId
        this.visible = true;
        this.$nextTick(() => {
          this.$refs["dataForm"].resetFields();
          this.$refs.replaceUploader.clearFiles();
          if (this.dataForm.id) {
            this.$http({
              url: this.$http.adornUrl(
                `/course/bookchapter/collegeCourseInfo/${this.dataForm.id}`
              ),
              method: "get",
              params: this.$http.adornParams()
            }).then(({data}) => {
              if (data && data.code === 0) {
                this.dataForm.chapterName = data.courseInfo.chapterName;
                this.dataForm.courseCoverUrl = data.courseInfo.courseCoverUrl;
                this.dataForm.chapterDesc = data.courseInfo.chapterDesc;
                this.dataForm.sourceInfo = data.courseInfo.sourceInfo;
                this.dataForm.wordNumber = data.courseInfo.wordNumber;
                this.dataForm.chapterVisit = data.courseInfo.chapterVisit;
                this.dataForm.sourceInfo = this.dataForm.sourceInfo ? JSON.parse(this.dataForm.sourceInfo) : {};
                if (this.dataForm.sourceInfo && this.dataForm.sourceInfo.video_duration) {
                  const duration = this.dataForm.sourceInfo.video_duration / 1000
                  const hour = parseInt(duration / 3600) < 10 ? '0' + parseInt(duration / 3600) : parseInt(duration / 3600)
                  const minute = parseInt(duration % 3600 / 60) < 10 ? '0' + parseInt(duration % 3600 / 60) : parseInt(duration % 3600 / 60)
                  const second = parseInt(duration % 60) < 10 ? '0' + parseInt(duration % 60) : parseInt(duration % 60)
                  this.dataForm.video_duration = `${hour}:${minute}:${second}`
                }
                this.dataForm.content = data.courseInfo.content;
                this.ue.ready(() => {
                  this.ue.setContent(this.dataForm.content);
                });
              }
            });
          } else {
            this.dataForm = {
              courseCoverUrl: '',
              sourceInfo: {
                video_url: "",
                cover_url: '',//视频封面URL
              },
            }
          }
        });
      },
      handleAvatarSuccess(response, file, fileList) {
        this.replaceList = fileList;
        this.successNum++;
        if (response && response.code === 0) {
          if (this.num === this.successNum) {
            this.$confirm("操作成功, 是否继续操作?", "提示", {
              confirmButtonText: "确定",
              cancelButtonText: "取消",
              type: "warning"
            }).catch(() => {
              this.visible = false;
            });
          }
        } else {
          this.$message.error(response.msg);
        }
      },
      // 上传音频
      beforeAvatarUpload(file) {
        var testmsg = file.name.substring(file.name.lastIndexOf(".") + 1);

        const extension = testmsg === "mp3";
        if (!extension) {
          this.$message({
            message: "上传文件只能是mp3格式！",
            type: "error"
          });
        } else {
          // 移除音频以便重新加载音频文件
          this.removefile();
        }
        return extension;
      },
      // 改变上传的时候取最后一个，实现替换上传
      handleChange(files, fileList) {
        // 获取最后一次得到的文件
        const aa = fileList[fileList.length - 1];
        // 覆盖上一次的文件
        this.replaceList = [];
        this.replaceList.push(aa);
      },
      handleChange1(files, fileList) {
        // 获取最后一次得到的文件
        const aa = fileList[fileList.length - 1];
        // 覆盖上一次的文件
        this.replaceList1 = [];
        this.replaceList1.push(aa);
      },
      handleChange2(files, fileList) {
        // 获取最后一次得到的文件
        const aa = fileList[fileList.length - 1];
        // 覆盖上一次的文件
        this.replaceList2 = [];
        this.replaceList2.push(aa);
      },
      //上传视频
      beforeUploadVideo(file) {
        this.dataForm.sourceInfo.video_size = file.size;
        if (
          [
            "video/mp4"
          ].indexOf(file.type) == -1
        ) {
          this.replaceList1 = []
          this.$message.error("请上传正确的视频格式");
          return false
        } else if(file.size / 1024 /1024 > 150){
          this.replaceList1 = []
          this.$message.error("上传的视频请小于150M");
          return false
        }else {
          this.removefile1();
        }
      },
      //视频上传成功
      handleVideoSuccess(response, file, fileList) {
        this.replaceList1 = fileList;
        this.successNum++;
        if (response && response.code === 0) {
          if (this.num === this.successNum) {
            this.$confirm("操作成功, 是否继续操作?", "提示", {
              confirmButtonText: "确定",
              cancelButtonText: "取消",
              type: "warning"
            }).catch(() => {
              this.visible = false;
            });
          }
          this.dataForm.sourceInfo.video_url = response.videoUrl;
          this.dataForm.sourceInfo.video_name = response.videoName;
        } else {
          this.$message.error(response.msg);
        }
      },
      // 上传视频封面
      handleimgSuccess(res, file) {
        this.dataForm.sourceInfo.cover_url = res.coverUrl;
        this.dataForm.sourceInfo.cover_name = res.coverName;
      },
      beforeimgUpload(file) {
        const isType = file.type === 'image/jpg' || file.type === 'image/jpeg' || file.type === 'image/png'
        if (!isType) {
          this.$message.error('上传封面图片只能是 png/jpg/jpeg 格式!');
        } else {
          this.removefile2();
        }
        const is250K = file.size / 1024 < 250
        if (!is250K) {
          this.$message.error('上传的图片要小于250KB!')
        }
        const isSize = new Promise(function (resolve, reject) {
          let _URL = window.URL || window.webkitURL
          let img = new Image()
          img.onload = function () {
            let valid = Math.round(img.width / img.height) == 2;
            valid ? resolve() : reject();
          };
          img.src = _URL.createObjectURL(file);
        }).then(
          () => {
            return file;
          },
          () => {
            this.$message.error("上传的视频封面必须是16:9!");
            return Promise.reject();
          }
        );
        return isType && isSize && is250K
      },
      // 表单提交
      getContent() {
        const durationArr = this.dataForm.video_duration?this.dataForm.video_duration.split(':'):''
        this.dataForm.sourceInfo.video_duration = durationArr[0] * 60 * 60 * 1000 + durationArr[1] * 60 * 1000 + durationArr[2] * 1000
        let that = this;
        this.ue.ready(() => {
          this.ueContent = this.ue.getContent();
          this.dataForm.content = this.ue.getContent();
        });
        this.$refs["dataForm"].validate(valid => {
          if (valid) {
            this.$http({
              url: this.$http.adornUrl(
                `/course/bookchapter/${!this.dataForm.id ? "saveCollegeCourse" : "updateCollegeCourse"}`
              ),
              method: "post",
              data: this.$http.adornData({
                bookId: this.bookId,
                chapterName: this.dataForm.chapterName,
                sourceInfo: JSON.stringify(this.dataForm.sourceInfo),
                content: this.ueContent.replace(/!thumbnail/g,''),
                courseCoverUrl: this.dataForm.courseCoverUrl,
                chapterVisit: this.dataForm.chapterVisit,
                id: this.dataForm.id || undefined,
              })
            }).then(({data}) => {
              if (data && data.code === 0) {
                this.$message({
                  message: "操作成功",
                  type: "success",
                  duration: 1500,
                  onClose: () => {
                    this.visible = false;
                    this.$emit("refresh", this.bookId);
                  }
                });
                that.ue.execCommand("cleardoc");
              } else {
                this.$message.error(data.msg);
              }
            });
          }
        });
      }
    }
  };
</script>
